package service

import (
	"fmt"
	"ginchat/config"
	"ginchat/models"
	"ginchat/repo"
	"ginchat/utils"
	"github.com/asaskevich/govalidator"
	"github.com/gin-gonic/gin"
)

func GetUserList(c *gin.Context) {
	data := repo.GetUserList()
	type UserList struct {
		Id       int64  `json:"id"`
		UserName string `json:"user_name"`
		NickName string `json:"nick_name"`
	}
	var userList []UserList

	for _, v := range data {
		itemUser := UserList{
			Id:       v.Id,
			UserName: v.UserName,
			NickName: v.Name,
		}
		userList = append(userList, itemUser)
	}
	if data == nil {
		CommonCJsonReply(c, config.ERROR, "获取数据db失败")
	}
	CommonCJsonReply(c, config.SUCCESS, userList)
}

func CreateUser(c *gin.Context) {
	user := models.UserBasic{}
	if err := c.ShouldBindBodyWithJSON(&user); err != nil {
		fmt.Println("请求参数错误", err)
		CommonCJsonReply(c, config.ERROR, "请求参数错误")
		return
	}
	// 查询用户是否存在
	existUser := repo.GetUserByUserName(user.UserName)
	if existUser != nil {
		CommonCJsonReply(c, config.ERROR, "用户已存在")
		return
	}
	// 把密码加密
	md5Pwd := utils.MakePassword(user.PassWord)
	user.PassWord = md5Pwd

	res := repo.CreateUser(&user)
	if res != nil {
		fmt.Println("创建用户失败", res)
		CommonCJsonReply(c, config.ERROR, "创建用户失败")
		return
	}
	CommonCJsonReply(c, config.SUCCESS, "")
}

func DelUser(c *gin.Context) {
	user := models.UserBasic{}
	if err := c.ShouldBindBodyWithJSON(&user); err != nil {
		fmt.Println("请求参数错误", err)
		CommonCJsonReply(c, config.ERROR, "请求参数错误")
		return
	}
	// 查询用户是否存在
	existUser := repo.GetUserByID(user.Id)
	if existUser == nil {
		CommonCJsonReply(c, config.ERROR, "用户不存在")
		return
	}
	fmt.Println("请求existUser", existUser)
	res := repo.DeleteUser(existUser.Id)
	if res != nil {
		fmt.Println("删除用户失败", res)
		CommonCJsonReply(c, config.ERROR, "删除用户失败")
		return
	}
	CommonCJsonReply(c, config.SUCCESS, "删除成功")
}

func UpdateUser(c *gin.Context) {
	user := models.UserBasic{}
	if err := c.ShouldBindBodyWithJSON(&user); err != nil {
		fmt.Println("请求参数错误", err)
		CommonCJsonReply(c, config.ERROR, "请求参数错误")
		return
	}
	_, err := govalidator.ValidateStruct(user)
	if err != nil {
		CommonCJsonReply(c, config.ERROR, "参数有误"+err.Error())
		return
	}
	// 查询用户是否存在
	existUser := repo.GetUserByID(user.Id)
	if existUser == nil {
		CommonCJsonReply(c, config.ERROR, "用户不存在")
		return
	}
	fmt.Println("请求existUser", existUser)
	res := repo.UpdateUser(&user)
	if res != nil {
		fmt.Println("更新用户失败", res)
		CommonCJsonReply(c, config.ERROR, "更新用户失败")
		return
	}
	CommonCJsonReply(c, config.SUCCESS, "更新成功")
}
